<?php
namespace Attendance\Controller;
use Common\Controller\AdminbaseController;
use Home\Service\ApplyService;
// +----------------------------------------------------------------------
// | Date:2017年3月6日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class ApplyController extends AdminbaseController{
    public function _initialize(){
        parent::_initialize();
        $this->model = D('Apply');
    }
    
    public function index(){
        
        $type = I('type');
        $dep_id = I('dep_id');
        $name = I('name');
        $start_time = I('start_time');
        $end_time = I('end_time');
        $vacation = I('vacation');
        
        $create_start = I('create_start');
        $create_end = I('create_end');
        
        $where = json_decode(urldecode(I('map')),true);
        
        if ($name)  $where['name'] = ['like',"%$name%"];
        if ($type)  $where['type'] = $type;
        if ($vacation)  $where['vacate_type'] = $vacation;
        if ($dep_id)  $where['dep_id'] = $dep_id;
        if ($start_time || $create_end) $where["_string"] = "(DATE_FORMAT(start_time,'%Y-%m-%d') >= '$start_time' AND DATE_FORMAT(start_time,'%Y-%m-%d') <= '$end_time') OR (DATE_FORMAT(end_time,'%Y-%m-%d') >= '$start_time' AND DATE_FORMAT(end_time,'%Y-%m-%d') <= '$end_time')";
        
        if ($create_start && $create_end) $where['created_time'] = ['between',["$create_start 00:00:00","$create_end 23:59:59"]];
        $where['status']=['neq','3'];
        
        
        if (I('print')) {
            $list = $this->model->where($where)->order('id desc')->select();
        }else{
            $list = $this->lists($this->model,$where,'id desc');
        }
        $type = C('APPLY_TYPE');
        $vacation = C('VACATION_TYPE');
        $leave_evection = C('LEAVE_TYPE');
        $ot = C('OT_TYPE');
        $leave_evection[] = $ot[0];
        $leave_evection[] = $ot[1];
        foreach($leave_evection as $k=>$v){
            $vacation[$v['value']] = $v['title'];
        }
        $this->assign('vacation',$vacation);
        $this->assign('type',$type);
        $this->assign('list',$list);
        $this->assign('status',['0'=>'待审核','1'=>'已通过','2'=>'已拒绝']);
        
        $this->show_print(ACTION_NAME,'请假报表');
        if ($where) $this->assign('map',urlencode(json_encode($where)));
        
        $this->display();
    }
    
    /**
     * 销毁申请数据
     * 1.修改目标数据状态，2删除日常考勤数据，进行重建，3通过那个时间段的全部申请数据
     * 
     * date:2017年5月15日
     * author: EK_熊
     */
    public function destroy(){
        $appid = I('id');
        $appInfo = $this->model->where(['id'=>$appid])->find();
        
        //修改目标申请数据的状态为3
        $updateApply = $this->model->where(['id'=>$appid])->setField('status',3);
        if ($appInfo['status'] == 1) {
            $attdanceDay = D('AttendanceDay');
            $approverModel = D('Approver');
            $totalDay = diff_days($appInfo['start_time'], $appInfo['end_time']);
            for ($i=0;$i<$totalDay;$i++){
                $day = date('Y-m-d',(strtotime($appInfo['start_time'])+86400*$i));
                $ret = $attdanceDay->att_day_rebuild($day,$appInfo['name']);//数据重建
                if ($ret){
                    $ret_str[]="[$day]重置完成";
                }else{
                    $ret_str[]="[$day]重置失败".$attdanceDay->getError();
                }
            }
            
            //恢复申请数据，全日薪，半日薪，  年假
            $this->recover_by_type($appInfo);
            var_dump($ret_str);
        }else{
            
            $this->success('撤销完成！！',U('index'));
        }
        
    }
    
    /**
     * 根据申请类型恢复表数据
     * 包括：全日薪，半日薪，  年假，调休    
     * @param unknown $appInfo
     * date:2018年3月2日
     * author: EK_熊
     */
    public function recover_by_type($appInfo){
        $apply_min = intval($appInfo['total_min']);
        if (in_array($appInfo['vacate_type'],[109,103,110])){
            $annualModel = M('AnnualLeave');
            $annualInfo = $annualModel->where(['sn'=>$appInfo['sn']])->order('start_date DESC')->find();
        }
        /* 年假 */
        if ($appInfo['vacate_type']==103) {
            $consume_min = intval($annualInfo['consume_min']);
            $adjust_consume = intval($annualInfo['adjust_consume']);
        
            $adjust_data = $consume_min-$apply_min;
        
            if ($adjust_data < 0){
                $saveAnnual['consume_min'] = 0;
                $save_consume = $adjust_consume+$adjust_data;
                $saveAnnual['adjust_consume'] = $save_consume >=0 ? $save_consume: 0;
            }else{
                $save_consume = $consume_min-$apply_min;
                $saveAnnual['consume_min'] = $save_consume >=0 ? $save_consume: 0;
            }
            $modifyAnnual = $annualModel->where(['id'=>$annualInfo['id']])->save($saveAnnual);
        } 
        /* 全日薪  */
        if ($appInfo['vacate_type']==109) {
            $sick_total = intval($annualInfo['sick_full_total']);
            $sick_remain = intval($annualInfo['sick_full_remain']);
            $save_repaire = $sick_remain+$apply_min;
            $saveAnnual['sick_full_remain'] = $save_repaire>$sick_total ? $sick_total : $save_repaire;
            $modifyAnnual = $annualModel->where(['id'=>$annualInfo['id']])->save($saveAnnual);
        }
        /* 半日薪  */
        if ($appInfo['vacate_type']==110) {
            $sick_total = intval($annualInfo['sick_half_total']);
            $sick_remain = intval($annualInfo['sick_half_remain']);
            $save_repaire = $sick_remain+$apply_min;
            $saveAnnual['sick_half_remain'] = $save_repaire>$sick_total ? $sick_total : $save_repaire;
            $modifyAnnual = $annualModel->where(['id'=>$annualInfo['id']])->save($saveAnnual);
        }
        
        /* 调休 */
        if ($appInfo['vacate_type']==101){
            $attDayModel = D('AttendanceDay');
            $txmap['sn'] = $appInfo['sn'];
            $txmap['compensatory_consume'] = ['gt',0];
            $txmap['date'] = ['lt',date('Y-m-d',strtotime($appInfo['created_time']))];
            $remain = $apply_min;//剩余数 等于 总数值
            while($remain > 0){
                $attDayInfo = $attDayModel->where($txmap)->order('date DESC')->field('id,date,compensatory_consume')->find();
                $compensatory_consume = intval($attDayInfo['compensatory_consume']);
                if ($compensatory_consume <= $remain){
                    $update = $attDayModel->where(['id'=>$attDayInfo['id']])->setField('compensatory_consume',0);
                }else{
                    $update = $attDayModel->where(['id'=>$attDayInfo['id']])->setDec('compensatory_consume',$remain);
                }
                
                $txmap['date'] = ['lt',$attDayInfo['date']];
                $remain -= $compensatory_consume;//剩余数
                
            }
            
        }
        
    }
    
    
    
    /**
     * 审核通过，操作单条记录
     *
     * date:2017年2月27日
     * author: EK_熊
     */
    public function auditPass(){
        $appid = I('id');
        $sn = C('SYS_SN');
        $approverModel = D('Approver');
        $ret = $approverModel->action_pass($appid,$sn);
        if (!$ret) $this->error($approverModel->getError());
        $this->success('操作完成！');
    
    }
    
    /**
     * 补申请
     * 
     * date:2018年4月4日
     * author: EK_熊
     */
    public function re_apply(){
        if (IS_POST) {
            $post = I('post');
            
            //提交检查
            if (empty($post['sn'])) $this->error('请填写姓名');
            if (empty($post['vacate_type'])) $this->error('请选择类型！');
            if (empty($post['content'])) $this->error('请填写申请理由！');
            if (empty($post['start_time']) || empty($post['end_time'])) $this->error('请填写申请时间！');
            
            //获取申请数据
            $applyService = new ApplyService();
            $appInfo = $applyService->create_apply_info($post['sn'],$post,true);
            
            //重复申请检查
            $applyModel = D('Apply');
            $isApply = $applyModel->where($appInfo)->find();
            if ($isApply) $this->error('请勿重复提交申请！！');
            
            //写入申请数据

            $appInfo['created_time'] = CURRENT_TIME;
            $appInfo['status'] = 1;
            
           $applyId = $applyModel->add($appInfo);
           if (!$applyId) $this->error('网络异常，数据添加失败！');
            
            //审批数据
            $approver = D('Approver')->_action_pass($applyId);
            if (!$approver) $this->error($this->model->getError());
            $this->success('操作完成！！');
            exit();
        }
        $this->display();
    }
    
    /**
     * 给前端联动获取假期类型
     * 
     * date:2018年4月4日
     * author: EK_熊
     */
    public function ajax_vacate_type(){
        $type = I('type');
        
        switch($type){
            case 1: 
                foreach (C('LEAVE_TYPE') as $k=> $v){
                    $vacate_type[] = "<option value=\"{$v['value']}\">{$v['title']}</option>";
                }
                break;
            case 2: 
                foreach (C('VACATION_TYPE') as $k=>$v){
                    
                    $vacate_type[] = "<option value=\"{$k}\">$v</option>";
                }
                break;
            case 3: 
                foreach (C('OT_TYPE') as $k=> $v){
                    $vacate_type[] = "<option value=\"{$v['value']}\">{$v['title']}</option>";
                }
                break;
        }
        $this->ajaxReturn(['data'=>$vacate_type]);
        
    }
    
    
}